package com.ningxun.pagentcrawler.controller.task;

import com.github.pagehelper.PageHelper;
import com.ningxun.pagent.common.core.controller.BaseController;
import com.ningxun.pagent.common.core.domain.AjaxResult;
import com.ningxun.pagent.common.core.page.TableDataInfo;
import com.ningxun.pagentcrawler.entity.CrawlerTask;
import com.ningxun.pagentcrawler.entity.task.CrawlerTaskEntity;
import com.ningxun.pagentcrawler.service.task.ICrawlerTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 爬虫任务管理Controller
 * 
 * @author pagent
 * @date 2025-01-XX
 */
@RestController
@RequestMapping("/system/crawler/task")
public class CrawlerTaskController extends BaseController {
    
    @Autowired
    private ICrawlerTaskService crawlerTaskService;
    
    /**
     * 查询爬虫任务列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CrawlerTask task,
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<CrawlerTaskEntity> list = crawlerTaskService.getAllTasks(task);
        return getDataTable(list);
    }
    
    /**
     * 获取爬虫任务详细信息
     */
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") String taskId) {
        return success(crawlerTaskService.getTaskById(taskId));
    }
    
    /**
     * 执行爬虫任务
     */
    @PostMapping("/execute")
    public AjaxResult execute(@RequestBody Map<String, Object> params) {
        String configId = (String) params.get("configId");
        CrawlerTask task = crawlerTaskService.startTask(configId, params);
        return success(task);
    }
    
    /**
     * 停止爬虫任务
     */
    @PostMapping("/stop/{taskId}")
    public AjaxResult stop(@PathVariable String taskId) {
        crawlerTaskService.stopTask(taskId);
        return success();
    }
    
    /**
     * 获取任务状态
     */
    @GetMapping("/status/{taskId}")
    public AjaxResult getStatus(@PathVariable String taskId) {
        String status = crawlerTaskService.getTaskStatus(taskId);
        return success(status);
    }
    
    /**
     * 获取任务详细信息（包含实时状态）
     */
    @GetMapping("/detail/{taskId}")
    public AjaxResult getTaskDetail(@PathVariable String taskId) {
        CrawlerTask task = crawlerTaskService.getTaskById(taskId);
        if (task != null) {
            // 获取实时状态
            String realTimeStatus = crawlerTaskService.getTaskStatus(taskId);
            task.setStatus(realTimeStatus);
        }
        return success(task);
    }
    
    /**
     * 获取所有运行中任务的状态
     */
    @GetMapping("/running-status")
    public AjaxResult getRunningTasksStatus() {
        List<CrawlerTask> allTasks = crawlerTaskService.getAllTasks();
        List<Map<String, Object>> runningTasks = new ArrayList<>();
        
        for (CrawlerTask task : allTasks) {
            if ("RUNNING".equals(task.getStatus())) {
                Map<String, Object> taskStatus = new HashMap<>();
                taskStatus.put("taskId", task.getId());
                taskStatus.put("taskName", task.getTaskName());
                taskStatus.put("status", crawlerTaskService.getTaskStatus(task.getId()));
                taskStatus.put("startTime", task.getStartTime());
                taskStatus.put("crawledCount", task.getCrawledCount());
                taskStatus.put("savedCount", task.getSavedCount());
                taskStatus.put("failedCount", task.getFailedCount());
                runningTasks.add(taskStatus);
            }
        }
        
        return success(runningTasks);
    }
    
    /**
     * 删除爬虫任务
     */
    @DeleteMapping("/{taskId}")
    public AjaxResult delete(@PathVariable String taskId) {
        crawlerTaskService.deleteTask(taskId);
        return success();
    }
    
    /**
     * 批量删除爬虫任务
     */
    @DeleteMapping("/batch/{taskIds}")
    public AjaxResult batchDelete(@PathVariable String[] taskIds) {
        for (String taskId : taskIds) {
            crawlerTaskService.deleteTask(taskId);
        }
        return success();
    }
} 